<template>
  <div class="employee-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">员工姓名：</div>

      <el-input v-model.trim="params.name" clearable placeholder="请输入员工姓名" class="search-main" />
      <el-button type="primary" @click="searchRender">查询</el-button>

    </div>

    <div class="create-container">
      <el-button type="primary" @click="addEmployee">添加员工</el-button>

    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="employeeList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="员工姓名" width="180" prop="name" />
        <el-table-column label="登录账号" width="180" prop="userName" />
        <el-table-column label="联系方式" width="120" prop="phonenumber" />
        <el-table-column label="角色" width="120" prop="roleName" />
        <el-table-column label="状态">
          <template #default="scope">
            {{ scope.row.status === 1 ? "启用" : "禁用" }}
          </template>

        </el-table-column>

        <el-table-column label="添加时间" prop="createTime" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editEmployee(scope.row.id)">编辑</el-button>

            <el-button size="mini" type="text" @click="delEmployee(scope.row.id)">删除</el-button>

            <el-button size="mini" type="text" @click="open(scope.row.id)">重置密码</el-button>

          </template>

        </el-table-column>
      </el-table>

    </div>

    <div class="page-container">
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="pageChange"
      :current-page="params.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="params.pageSize"
      layout="total,  prev, pager, next, sizes, jumper"
      :total="total"
    >
    </el-pagination>
    </div>

    <!-- 添加员工 -->
    <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose"
    >
  <!-- 表单接口 -->
  <div class="form-container">
    <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px">
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="addForm.name" />
      </el-form-item>

      <el-form-item label="登录账号" prop="userName">
        <el-input v-model="addForm.userName" />
      </el-form-item>

      <el-form-item label="联系方式" prop="phonenumber">
        <el-input v-model="addForm.phonenumber" />
      </el-form-item>

      <el-form-item label="分配角色" prop="roleId">
        <el-select v-model="addForm.roleId" placeholder="请选择角色">
          <el-option
            v-for="item in roleList"
      :key="item.roleId"
      :label="item.roleName"
      :value="item.roleId"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="员工状态" prop="status">
        <el-radio-group v-model="addForm.status">
          <el-radio :label="0">禁用</el-radio>

          <el-radio :label="1">启用</el-radio>

        </el-radio-group>

      </el-form-item>

    </el-form>

  </div>

  <template #footer>
    <el-button @click="dialogVisible = false">取 消</el-button>

    <el-button type="primary" @click="confirmSubmit">确 定</el-button>

  </template>

</el-dialog>
  </div>
  
</template>

<script>
import { getEmployeeListAPI,getRoleListAPI,createEmployeeAPI,delEmployeeAPI,getEmployeeIdApi,resetPassword,putEmployeeAPI } from '@/api/employee'
import { Message } from 'element-ui'
export default {
  name: 'Employee',
  data() {
    return {
      total: 0,
      employeeList: [],
      params: {
        page: 1,
        pageSize: 10,
        name: '' // 员工姓名
      },
      dialogVisible: false, // 控制弹框打开关闭
    roleList: [], // 角色列表
    addForm: {
      id: '', // 新增id字段,编辑时使用
      name: '',
      phonenumber: '',
      roleId: '',
      status: 1,
      userName: ''
    },
    addFormRules: {
      name: [
        { required: true, message: '请输入员工姓名', trigger: 'blur' }
      ],
      userName: [
        { required: true, message: '请输入登录账号', trigger: 'blur' }
      ],
      phonenumber: [
        { required: true, message: '请输入联系方式', trigger: 'blur' }
      ],
      roleId: [
        { required: true, message: '请分配角色', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择员工状态', trigger: 'blur' }
      ]
    },
    isEdit: false // 新增标识,用于区分是编辑还是新增
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑员工' : '添加员工'
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    async searchRender(){
      this.getEmployeeList()
    },
    open(id) {
        this.$confirm('确定将密码重置为"123456"？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await resetPassword(id)
          Message.success('重置密码成功！');
        }).catch(() => {
          Message.info('已取消重置密码');         
        });
      },
    async editEmployee(id){
      try {
        // 获取员工详情
        let {data} = await getEmployeeIdApi(id);
        // 解构需要的字段,包括roleName
        let {name, userName, phonenumber, roleId, status, roleName} = data
        
        // 设置表单数据,包含所有必需字段和可选的roleName
        this.addForm = {
          id,  // 主键
          name, // 用户姓名
          userName, // 登录账号 
          phonenumber, // 联系方式
          roleId, // 角色ID
          status, // 状态
          roleName // 可选的角色名称
        }
        
        this.isEdit = true // 标记为编辑模式
        
        // 获取角色列表
        const res = await getRoleListAPI();
        this.roleList = res.data;
        
        this.dialogVisible = true;
      } catch(err) {
        console.log(err)
        this.$message.error('获取员工信息失败')
      }
    },
    delEmployee(id) {
  this.$confirm('删除员工后将不可登录，确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    await delEmployeeAPI(id)
    this.$message({
      type: 'success',
      message: '删除成功'
    })
    this.getEmployeeList()
  })
},
    async confirmSubmit() {
      try {
        // 表单验证
        await this.$refs.addForm.validate()
        
        if (this.isEdit) {
          // 编辑模式 - 构造完整的请求参数
          const editParams = {
            id: this.addForm.id,
            name: this.addForm.name,
            userName: this.addForm.userName,
            phonenumber: this.addForm.phonenumber,
            roleId: this.addForm.roleId,
            status: this.addForm.status,
            roleName: this.addForm.roleName // 可选字段
          }
          
          await putEmployeeAPI(editParams)
          this.$message.success('修改成功')
        } else {
          // 添加模式 - 不需要传id和roleName
          const addParams = {
            name: this.addForm.name,
            userName: this.addForm.userName,
            phonenumber: this.addForm.phonenumber,
            roleId: this.addForm.roleId,
            status: this.addForm.status
          }
          
          await createEmployeeAPI(addParams)
          this.$message.success('添加成功')
        }

        this.dialogVisible = false
        this.getEmployeeList() // 刷新列表
      } catch(err) {
        console.log(err)
        this.$message.error('操作失败')
      }
    },
    handleClose() {
      this.$refs.addForm.resetFields()
      this.dialogVisible = false
    },
    async addEmployee() {
      this.isEdit = false
      this.addForm = {
        id: '', // 主键
        name: '', // 用户姓名
        userName: '', // 登录账号
        phonenumber: '', // 联系方式
        roleId: '', // 角色ID
        status: 1, // 状态默认启用
        roleName: '' // 角色名称
      }
      
      // 获取角色列表
      const res = await getRoleListAPI();
      this.roleList = res.data;
      
      this.dialogVisible = true;
    },
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.params)
      this.employeeList = res.data.rows
      this.total = res.data.total;
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getEmployeeList();
    },
    pageChange(page) {
      this.params.page = page
      this.getEmployeeList()
    }
    
  },
  
}
</script>


<style lang="scss" scoped>
.employee-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 20px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
::v-deep .el-table__header-wrapper th {
  background-color: #f4f6f8;
}
::v-deep .el-pagination {
  margin-top: 30px;
  text-align: right;
}
::v-deep .el-message-box__content{
  background-color: red;
  width: 100%;
  text-align: center;
  font-weight: 700;
}
</style>
